<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: Introduction to Java Development</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../df/d65/tutorial_table_of_content_introduction.html">Introduction to OpenCV</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">Introduction to Java Development </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d4/d14/tutorial_windows_visual_studio_image_watch.html">Image Watch: viewing in-memory images in the Visual Studio debugger</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../d1/d0a/tutorial_java_eclipse.html">Using OpenCV Java with Eclipse</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Eric Christiansen and Andrey Pavlenko </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<dl class="section warning"><dt>Warning</dt><dd>This tutorial can contain obsolete information.</dd></dl>
<p>As of OpenCV 2.4.4, OpenCV supports desktop Java development using nearly the same interface as for Android development. This guide will help you to create your first Java (or Scala) application using OpenCV. We will use either <a href="http://ant.apache.org/">Apache Ant</a> or <a href="http://www.scala-sbt.org/">Simple Build Tool (SBT)</a> to build the application.</p>
<p>If you want to use Eclipse head to <a class="el" href="../../d1/d0a/tutorial_java_eclipse.html">Using OpenCV Java with Eclipse</a>. For further reading after this guide, look at the <a class="el" href="../../d9/d3f/tutorial_android_dev_intro.html">Introduction into Android Development</a> tutorials.</p>
<h2>What we'll do in this guide </h2>
<p>In this guide, we will:</p>
<ul>
<li>Get OpenCV with desktop Java support</li>
<li>Create an Ant or SBT project</li>
<li>Write a simple OpenCV application in Java or Scala</li>
</ul>
<p>The same process was used to create the samples in the <code>samples/java</code> folder of the OpenCV repository, so consult those files if you get lost.</p>
<h2>Get proper OpenCV </h2>
<p>Starting from version 2.4.4 OpenCV includes desktop Java bindings.</p>
<h3>Download</h3>
<p>The most simple way to get it is downloading the appropriate package of <b>version 2.4.4 or higher</b> from the <a href="http://sourceforge.net/projects/opencvlibrary/files/">OpenCV SourceForge repository</a>.</p>
<dl class="section note"><dt>Note</dt><dd>Windows users can find the prebuilt files needed for Java development in the <code>opencv/build/java/</code> folder inside the package. For other OSes it's required to build OpenCV from sources.</dd></dl>
<p>Another option to get OpenCV sources is to clone <a href="https://github.com/opencv/opencv/">OpenCV git repository</a>. In order to build OpenCV with Java bindings you need JDK (Java Development Kit) (we recommend <a href="http://www.oracle.com/technetwork/java/javase/downloads/">Oracle/Sun JDK 6 or 7</a>), <a href="http://ant.apache.org/">Apache Ant</a> and Python v2.6 or higher to be installed.</p>
<h3>Build</h3>
<p>Let's build OpenCV: </p><div class="fragment"><div class="line">git clone git://github.com/opencv/opencv.git</div><div class="line">cd opencv</div><div class="line">git checkout 2.4</div><div class="line">mkdir build</div><div class="line">cd build</div></div><!-- fragment --><p> Generate a Makefile or a MS Visual Studio* solution, or whatever you use for building executables in your system: </p><div class="fragment"><div class="line">cmake -DBUILD_SHARED_LIBS=OFF ..</div></div><!-- fragment --><p> or </p><div class="fragment"><div class="line">cmake -DBUILD_SHARED_LIBS=OFF -G &quot;Visual Studio 10&quot; ..</div></div><!-- fragment --><dl class="section note"><dt>Note</dt><dd>When OpenCV is built as a set of <b>static</b> libraries (-DBUILD_SHARED_LIBS=OFF option) the Java bindings dynamic library is all-sufficient, i.e. doesn't depend on other OpenCV libs, but includes all the OpenCV code inside.</dd></dl>
<p>Examine the output of CMake and ensure java is one of the modules "To be built". If not, it's likely you're missing a dependency. You should troubleshoot by looking through the CMake output for any Java-related tools that aren't found and installing them.</p>
<div class="image">
<img src="../../cmake_output.png" alt="cmake_output.png"/>
</div>
<dl class="section note"><dt>Note</dt><dd>If CMake can't find Java in your system set the JAVA_HOME environment variable with the path to installed JDK before running it. E.g.: <div class="fragment"><div class="line">export JAVA_HOME=/usr/lib/jvm/java-6-oracle</div><div class="line">cmake -DBUILD_SHARED_LIBS=OFF ..</div></div><!-- fragment --></dd></dl>
<p>Now start the build: </p><div class="fragment"><div class="line">make -j8</div></div><!-- fragment --><p> or </p><div class="fragment"><div class="line">msbuild /m OpenCV.sln /t:Build /p:Configuration=Release /v:m</div></div><!-- fragment --><p> Besides all this will create a jar containing the Java interface (<code>bin/opencv-244.jar</code>) and a native dynamic library containing Java bindings and all the OpenCV stuff (<code>lib/libopencv_java244.so</code> or <code>bin/Release/opencv_java244.dll</code> respectively). We'll use these files later.</p>
<h2>Java sample with Ant </h2>
<dl class="section note"><dt>Note</dt><dd>The described sample is provided with OpenCV library in the <code>opencv/samples/java/ant</code> folder.</dd></dl>
<ul>
<li>Create a folder where you'll develop this sample application.</li>
<li>In this folder create the <code>build.xml</code> file with the following content using any text editor: <div class="fragment"><div class="line">&lt;<span class="keywordtype">project</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;SimpleSample&quot;</span> <span class="keyword">basedir</span>=<span class="stringliteral">&quot;.&quot;</span> <span class="keyword">default</span>=<span class="stringliteral">&quot;rebuild-run&quot;</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;src.dir&quot;</span>     <span class="keyword">value</span>=<span class="stringliteral">&quot;src&quot;</span>/&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;lib.dir&quot;</span>     <span class="keyword">value</span>=<span class="stringliteral">&quot;${ocvJarDir}&quot;</span>/&gt;</div><div class="line">    &lt;<span class="keywordtype">path</span> <span class="keyword">id</span>=<span class="stringliteral">&quot;classpath&quot;</span>&gt;</div><div class="line">        &lt;<span class="keywordtype">fileset</span> <span class="keyword">dir</span>=<span class="stringliteral">&quot;${lib.dir}&quot;</span> <span class="keyword">includes</span>=<span class="stringliteral">&quot;**/*.jar&quot;</span>/&gt;</div><div class="line">    &lt;/<span class="keywordtype">path</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;build.dir&quot;</span>   <span class="keyword">value</span>=<span class="stringliteral">&quot;build&quot;</span>/&gt;</div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;classes.dir&quot;</span> <span class="keyword">value</span>=<span class="stringliteral">&quot;${build.dir}/classes&quot;</span>/&gt;</div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;jar.dir&quot;</span>     <span class="keyword">value</span>=<span class="stringliteral">&quot;${build.dir}/jar&quot;</span>/&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">property</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;main-class&quot;</span>  <span class="keyword">value</span>=<span class="stringliteral">&quot;${ant.project.name}&quot;</span>/&gt;</div><div class="line"></div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;clean&quot;</span>&gt;</div><div class="line">        &lt;<span class="keywordtype">delete</span> <span class="keyword">dir</span>=<span class="stringliteral">&quot;${build.dir}&quot;</span>/&gt;</div><div class="line">    &lt;/<span class="keywordtype">target</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;compile&quot;</span>&gt;</div><div class="line">        &lt;<span class="keywordtype">mkdir</span> <span class="keyword">dir</span>=<span class="stringliteral">&quot;${classes.dir}&quot;</span>/&gt;</div><div class="line">        &lt;<span class="keywordtype">javac</span> <span class="keyword">includeantruntime</span>=<span class="stringliteral">&quot;false&quot;</span> <span class="keyword">srcdir</span>=<span class="stringliteral">&quot;${src.dir}&quot;</span> <span class="keyword">destdir</span>=<span class="stringliteral">&quot;${classes.dir}&quot;</span> <span class="keyword">classpathref</span>=<span class="stringliteral">&quot;classpath&quot;</span>/&gt;</div><div class="line">    &lt;/<span class="keywordtype">target</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;jar&quot;</span> <span class="keyword">depends</span>=<span class="stringliteral">&quot;compile&quot;</span>&gt;</div><div class="line">        &lt;<span class="keywordtype">mkdir</span> <span class="keyword">dir</span>=<span class="stringliteral">&quot;${jar.dir}&quot;</span>/&gt;</div><div class="line">        &lt;<span class="keywordtype">jar</span> <span class="keyword">destfile</span>=<span class="stringliteral">&quot;${jar.dir}/${ant.project.name}.jar&quot;</span> <span class="keyword">basedir</span>=<span class="stringliteral">&quot;${classes.dir}&quot;</span>&gt;</div><div class="line">            &lt;<span class="keywordtype">manifest</span>&gt;</div><div class="line">                &lt;<span class="keywordtype">attribute</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;Main-Class&quot;</span> <span class="keyword">value</span>=<span class="stringliteral">&quot;${main-class}&quot;</span>/&gt;</div><div class="line">            &lt;/<span class="keywordtype">manifest</span>&gt;</div><div class="line">        &lt;/<span class="keywordtype">jar</span>&gt;</div><div class="line">    &lt;/<span class="keywordtype">target</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;run&quot;</span> <span class="keyword">depends</span>=<span class="stringliteral">&quot;jar&quot;</span>&gt;</div><div class="line">        &lt;<span class="keywordtype">java</span> <span class="keyword">fork</span>=<span class="stringliteral">&quot;true&quot;</span> <span class="keyword">classname</span>=<span class="stringliteral">&quot;${main-class}&quot;</span>&gt;</div><div class="line">            &lt;<span class="keywordtype">sysproperty</span> <span class="keyword">key</span>=<span class="stringliteral">&quot;java.library.path&quot;</span> <span class="keyword">path</span>=<span class="stringliteral">&quot;${ocvLibDir}&quot;</span>/&gt;</div><div class="line">            &lt;<span class="keywordtype">classpath</span>&gt;</div><div class="line">                &lt;<span class="keywordtype">path</span> <span class="keyword">refid</span>=<span class="stringliteral">&quot;classpath&quot;</span>/&gt;</div><div class="line">                &lt;<span class="keywordtype">path</span> <span class="keyword">location</span>=<span class="stringliteral">&quot;${jar.dir}/${ant.project.name}.jar&quot;</span>/&gt;</div><div class="line">            &lt;/<span class="keywordtype">classpath</span>&gt;</div><div class="line">        &lt;/<span class="keywordtype">java</span>&gt;</div><div class="line">    &lt;/<span class="keywordtype">target</span>&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;rebuild&quot;</span> <span class="keyword">depends</span>=<span class="stringliteral">&quot;clean,jar&quot;</span>/&gt;</div><div class="line"></div><div class="line">    &lt;<span class="keywordtype">target</span> <span class="keyword">name</span>=<span class="stringliteral">&quot;rebuild-run&quot;</span> <span class="keyword">depends</span>=<span class="stringliteral">&quot;clean,run&quot;</span>/&gt;</div><div class="line"></div><div class="line">&lt;/<span class="keywordtype">project</span>&gt;</div></div><!-- fragment --> <dl class="section note"><dt>Note</dt><dd>This XML file can be reused for building other Java applications. It describes a common folder structure in the lines 3 - 12 and common targets for compiling and running the application. When reusing this XML don't forget to modify the project name in the line 1, that is also the name of the main class (line 14). The paths to OpenCV jar and jni lib are expected as parameters ("${ocvJarDir}" in line 5 and "${ocvLibDir}" in line 37), but you can hardcode these paths for your convenience. See <a href="http://ant.apache.org/manual/">Ant documentation</a> for detailed description of its build file format.</dd></dl>
</li>
<li>Create an <code>src</code> folder next to the <code>build.xml</code> file and a <code>SimpleSample.java</code> file in it.</li>
<li>Put the following Java code into the <code>SimpleSample.java</code> file: <div class="fragment"><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.CvType;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"></div><div class="line"><span class="keyword">class </span>SimpleSample {</div><div class="line"></div><div class="line">  <span class="keyword">static</span>{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }</div><div class="line"></div><div class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">    System.out.println(<span class="stringliteral">&quot;Welcome to OpenCV &quot;</span> + Core.VERSION);</div><div class="line">    Mat m = <span class="keyword">new</span> Mat(5, 10, CvType.CV_8UC1, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0));</div><div class="line">    System.out.println(<span class="stringliteral">&quot;OpenCV Mat: &quot;</span> + m);</div><div class="line">    Mat mr1 = m.row(1);</div><div class="line">    mr1.setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(1));</div><div class="line">    Mat mc5 = m.col(5);</div><div class="line">    mc5.setTo(<span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(5));</div><div class="line">    System.out.println(<span class="stringliteral">&quot;OpenCV Mat data:\n&quot;</span> + m.dump());</div><div class="line">  }</div><div class="line"></div><div class="line">}</div></div><!-- fragment --></li>
<li><p class="startli">Run the following command in console in the folder containing <code>build.xml</code>: </p><div class="fragment"><div class="line">ant -DocvJarDir=path/to/dir/containing/opencv-244.jar -DocvLibDir=path/to/dir/containing/opencv_java244/native/library</div></div><!-- fragment --><p> For example: </p><div class="fragment"><div class="line">ant -DocvJarDir=X:\opencv-2.4.4\bin -DocvLibDir=X:\opencv-2.4.4\bin\Release</div></div><!-- fragment --><p> The command should initiate [re]building and running the sample. You should see on the screen something like this:</p>
<div class="image">
<img src="../../ant_output.png" alt="ant_output.png"/>
</div>
</li>
</ul>
<h2>SBT project for Java and Scala </h2>
<p>Now we'll create a simple Java application using SBT. This serves as a brief introduction to those unfamiliar with this build tool. We're using SBT because it is particularly easy and powerful.</p>
<p>First, download and install <a href="http://www.scala-sbt.org/">SBT</a> using the instructions on its <a href="http://www.scala-sbt.org/">web site</a>.</p>
<p>Next, navigate to a new directory where you'd like the application source to live (outside <code>opencv</code> dir). Let's call it "JavaSample" and create a directory for it: </p><div class="fragment"><div class="line">cd &lt;somewhere outside opencv&gt;</div><div class="line">mkdir JavaSample</div></div><!-- fragment --><p> Now we will create the necessary folders and an SBT project: </p><div class="fragment"><div class="line">cd JavaSample</div><div class="line">mkdir -p src/main/java # This is where SBT expects to find Java sources</div><div class="line">mkdir project # This is where the build definitions live</div></div><!-- fragment --><p> Now open <code>project/build.scala</code> in your favorite editor and paste the following. It defines your project: </p><div class="fragment"><div class="line">import sbt._</div><div class="line">import Keys._</div><div class="line"></div><div class="line">object JavaSampleBuild extends Build {</div><div class="line">  def scalaSettings = Seq(</div><div class="line">    scalaVersion := &quot;2.10.0&quot;,</div><div class="line">    scalacOptions ++= Seq(</div><div class="line">      &quot;-optimize&quot;,</div><div class="line">      &quot;-unchecked&quot;,</div><div class="line">      &quot;-deprecation&quot;</div><div class="line">    )</div><div class="line">  )</div><div class="line"></div><div class="line">  def buildSettings =</div><div class="line">    Project.defaultSettings ++</div><div class="line">    scalaSettings</div><div class="line"></div><div class="line">  lazy val root = {</div><div class="line">    val settings = buildSettings ++ Seq(name := &quot;JavaSample&quot;)</div><div class="line">    Project(id = &quot;JavaSample&quot;, base = file(&quot;.&quot;), settings = settings)</div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p> Now edit <code>project/plugins.sbt</code> and paste the following. This will enable auto-generation of an Eclipse project: </p><div class="fragment"><div class="line">addSbtPlugin(&quot;com.typesafe.sbteclipse&quot; % &quot;sbteclipse-plugin&quot; % &quot;2.1.0&quot;)</div></div><!-- fragment --><p> Now run sbt from the <code>JavaSample</code> root and from within SBT run eclipse to generate an eclipse project: </p><div class="fragment"><div class="line">sbt # Starts the sbt console</div><div class="line">eclipse # Running &quot;eclipse&quot; from within the sbt console</div></div><!-- fragment --><p> You should see something like this:</p>
<div class="image">
<img src="../../sbt_eclipse.png" alt="sbt_eclipse.png"/>
</div>
<p>You can now import the SBT project to Eclipse using Import ... -&gt; Existing projects into workspace. Whether you actually do this is optional for the guide; we'll be using SBT to build the project, so if you choose to use Eclipse it will just serve as a text editor.</p>
<p>To test that everything is working, create a simple "Hello OpenCV" application. Do this by creating a file <code>src/main/java/HelloOpenCV.java</code> with the following contents: </p><div class="fragment"><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>HelloOpenCV {</div><div class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">    System.out.println(<span class="stringliteral">&quot;Hello, OpenCV&quot;</span>);</div><div class="line"> }</div></div><!-- fragment --><p> }</p>
<p>Now execute run from the sbt console, or more concisely, run sbt run from the command line: </p><div class="fragment"><div class="line">sbt run</div></div><!-- fragment --><p> You should see something like this:</p>
<div class="image">
<img src="../../sbt_run.png" alt="sbt_run.png"/>
</div>
<h3>Running SBT samples</h3>
<p>Now we'll create a simple face detection application using OpenCV.</p>
<p>First, create a <code>lib/</code> folder and copy the OpenCV jar into it. By default, SBT adds jars in the lib folder to the Java library search path. You can optionally rerun sbt eclipse to update your Eclipse project. </p><div class="fragment"><div class="line">mkdir lib</div><div class="line">cp &lt;opencv_dir&gt;/build/bin/opencv_&lt;version&gt;.jar lib/</div><div class="line">sbt eclipse</div></div><!-- fragment --><p> Next, create the directory <code>src/main/resources</code> and download this Lena image into it:</p>
<div class="image">
<img src="../../lena.png" alt="lena.png"/>
</div>
<p>Make sure it's called <code>"lena.png"</code>. Items in the resources directory are available to the Java application at runtime.</p>
<p>Next, copy <code>lbpcascade_frontalface.xml</code> from <code>opencv/data/lbpcascades/</code> into the <code>resources</code> directory: </p><div class="fragment"><div class="line">cp &lt;opencv_dir&gt;/data/lbpcascades/lbpcascade_frontalface.xml src/main/resources/</div></div><!-- fragment --><p> Now modify src/main/java/HelloOpenCV.java so it contains the following Java code: </p><div class="fragment"><div class="line"><span class="keyword">import</span> org.opencv.core.Core;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Mat;</div><div class="line"><span class="keyword">import</span> org.opencv.core.MatOfRect;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Point;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Rect;</div><div class="line"><span class="keyword">import</span> org.opencv.core.Scalar;</div><div class="line"><span class="keyword">import</span> org.opencv.imgcodecs.Imgcodecs;</div><div class="line"><span class="keyword">import</span> org.opencv.objdetect.CascadeClassifier;</div><div class="line"></div><div class="line"><span class="comment">//</span></div><div class="line"><span class="comment">// Detects faces in an image, draws boxes around them, and writes the results</span></div><div class="line"><span class="comment">// to &quot;faceDetection.png&quot;.</span></div><div class="line"><span class="comment">//</span></div><div class="line"><span class="keyword">class </span>DetectFaceDemo {</div><div class="line">  <span class="keyword">public</span> <span class="keywordtype">void</span> run() {</div><div class="line">    System.out.println(<span class="stringliteral">&quot;\nRunning DetectFaceDemo&quot;</span>);</div><div class="line"></div><div class="line">    <span class="comment">// Create a face detector from the cascade file in the resources</span></div><div class="line">    <span class="comment">// directory.</span></div><div class="line">    CascadeClassifier faceDetector = <span class="keyword">new</span> CascadeClassifier(getClass().getResource(<span class="stringliteral">&quot;/lbpcascade_frontalface.xml&quot;</span>).getPath());</div><div class="line">    Mat image = Imgcodecs.imread(getClass().getResource(<span class="stringliteral">&quot;/lena.png&quot;</span>).getPath());</div><div class="line"></div><div class="line">    <span class="comment">// Detect faces in the image.</span></div><div class="line">    <span class="comment">// MatOfRect is a special container class for Rect.</span></div><div class="line">    MatOfRect faceDetections = <span class="keyword">new</span> MatOfRect();</div><div class="line">    faceDetector.detectMultiScale(image, faceDetections);</div><div class="line"></div><div class="line">    System.out.println(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>.format(<span class="stringliteral">&quot;Detected %s faces&quot;</span>, faceDetections.toArray().length));</div><div class="line"></div><div class="line">    <span class="comment">// Draw a bounding box around each face.</span></div><div class="line">    <span class="keywordflow">for</span> (<a class="code" href="../../dc/d84/group__core__basic.html#ga11d95de507098e90bad732b9345402e8">Rect</a> rect : faceDetections.toArray()) {</div><div class="line">        Imgproc.rectangle(image, <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(rect.x, rect.y), <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga1e83eafb2d26b3c93f09e8338bcab192">Point</a>(rect.x + rect.width, rect.y + rect.height), <span class="keyword">new</span> <a class="code" href="../../dc/d84/group__core__basic.html#ga599fe92e910c027be274233eccad7beb">Scalar</a>(0, 255, 0));</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="comment">// Save the visualized detection.</span></div><div class="line">    <a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a> filename = <span class="stringliteral">&quot;faceDetection.png&quot;</span>;</div><div class="line">    System.out.println(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>.format(<span class="stringliteral">&quot;Writing %s&quot;</span>, filename));</div><div class="line">    Imgcodecs.imwrite(filename, image);</div><div class="line">  }</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">public</span> <span class="keyword">class </span>HelloOpenCV {</div><div class="line">  <span class="keyword">public</span> <span class="keyword">static</span> <span class="keywordtype">void</span> main(<a class="code" href="../../dc/d84/group__core__basic.html#ga1f6634802eeadfd7245bc75cf3e216c2">String</a>[] args) {</div><div class="line">    System.out.println(<span class="stringliteral">&quot;Hello, OpenCV&quot;</span>);</div><div class="line"></div><div class="line">    <span class="comment">// Load the native library.</span></div><div class="line">    System.loadLibrary(Core.NATIVE_LIBRARY_NAME);</div><div class="line">    <span class="keyword">new</span> DetectFaceDemo().run();</div><div class="line">  }</div><div class="line">}</div></div><!-- fragment --><p> Note the call to System.loadLibrary(Core.NATIVE_LIBRARY_NAME). This command must be executed exactly once per Java process prior to using any native OpenCV methods. If you don't call it, you will get UnsatisfiedLink errors. You will also get errors if you try to load OpenCV when it has already been loaded.</p>
<p>Now run the face detection app using `sbt run`: </p><div class="fragment"><div class="line">sbt run</div></div><!-- fragment --><p> You should see something like this:</p>
<div class="image">
<img src="../../sbt_run_face.png" alt="sbt_run_face.png"/>
</div>
<p>It should also write the following image to <code>faceDetection.png</code>:</p>
<div class="image">
<img src="../../faceDetection.png" alt="faceDetection.png"/>
</div>
<p>You're done! Now you have a sample Java application working with OpenCV, so you can start the work on your own. We wish you good luck and many years of joyful life! </p>
</div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:36 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
